package com.zhouxiao.multithreading.线程执行顺序;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * @author 周小哥  gqzmy@163.com 2023/3/3 22:40
 * <p>
 * 需求：
 * 1、1号线程、2号线程、3号线程都要执行
 * 2、执行是有顺序的，1->2->3
 * <p>
 * 实现：使用回环栏栅CyclicBarrier，使线程顺序执行
 * <p>
 * CyclicBarrier:让一组线程到达一个屏障时被阻塞，直到最后一个线程到达屏障时，屏障才会打开，所有被屏障拦截的线程将继续执行
 */

public class ThreadCyclicBarrierDemo {

    private static final CyclicBarrier cyclicBarrier_1 = new CyclicBarrier(2);
    private static final CyclicBarrier cyclicBarrier_2 = new CyclicBarrier(2);

    public static void main(String[] args) {
        Thread thread1 = new Thread(() -> {
            try {
                System.out.println("1号线程");
                cyclicBarrier_1.await();
            } catch (InterruptedException | BrokenBarrierException e) {
                throw new RuntimeException(e);
            }
        });

        Thread thread2 = new Thread(() -> {
            try {
                cyclicBarrier_1.await();
                System.out.println("2号线程");
                cyclicBarrier_2.await();
            } catch (InterruptedException | BrokenBarrierException e) {
                throw new RuntimeException(e);
            }
        });

        Thread thread3 = new Thread(() -> {
            try {
                cyclicBarrier_2.await();
                System.out.println("3号线程");
            } catch (InterruptedException | BrokenBarrierException e) {
                throw new RuntimeException(e);
            }
        });
        System.out.println("开始。。。");
        thread3.start();
        thread1.start();
        thread2.start();
    }

}
